/**
 * Created by leiweibo on 6/28/15.
 */

var app = angular.module('doctorcontroller', []);
var count = 0;

app.filter('offset', function () {
  return function (input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});


app.controller('DoctorCtrl', function ($scope, $window, $routeParams, upyun, DoctorService, HospitalService, ProvinceService, OfficeService, DoctorData) {
  $scope.add = function () {
    DoctorData.set(null);
    window.location = '#/create_doctor';
  };

  $scope.add_reasearch = function() {
    window.location = '#/create_doctor_research';
  };

  $scope.createOrUpdate = function () {
    var formData = {
      id: $scope.id,
      name: $scope.name,
      title: $scope.title,
      major: $scope.major,
      introduce: $scope.introduce,
      province: $scope.province,
      hospital: $scope.hospital,
      office: $scope.office,
      avatar: $scope.avatar,
      phone: $scope.phone
    }

    if ($scope.id) {
      DoctorService.update(formData, function (res) {
        if (res.result == true) {
          window.location = "#/doctor_list";
        } else {
          $scope.error_msg = res.message;
        }
      }, function (data, status) {
        if (status == 403) {
          $scope.error_msg = '无权限进行此操作';
        }
      })
    } else {
      DoctorService.create(formData, function (res) {
        if (res.result == true) {
          delete $scope.id,
            delete $scope.name,
            delete $scope.title,
            delete $scope.major,
            delete $scope.introduce
            delete $scope.province,
            delete $scope.hospital,
            delete $scope.office,
            delete $scope.avatar,
            delete $scope.phone,
            delete $scope.image_url,
            $scope.image_ready = false,
            $(".progress").addClass('hidden');
          $(".progress-bar").css("width", 0 + '%');
          $(".progress-bar").html(0 + '%');

          alert('添加或者修改医生信息成功');
        } else {
          $scope.error_msg = res.message;
        }
      }, function (data, status) {
        $scope.error_msg = '无权限进行此操作';
      })
    }

  };

  $scope.callServer = function (tableState) {
    $scope.isLoading = true;

    var pagination = tableState.pagination;
    var pageSize = pagination.number || 20;
    var pageNo = Math.ceil((pagination.start + 1) / pageSize) || 1;
    var hospital = $routeParams.param;
    DoctorService.list(hospital, pageNo, pageSize, tableState, function (res) {
      $scope.displayed = res.doctors;
      tableState.pagination.numberOfPages = res.pageCount;
      $scope.isLoading = false;
    });
  };

  $scope.provinceChanged = function (provinceId) {
    $scope.hospitals = HospitalService.list_by_province(provinceId, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.hospitals = res.hospitals;
    });
  };

  $scope.provinces = ProvinceService.list(function (data) {
    $scope.provinces = data.provinces
  });

  $scope.hospitalChanged = function (hospitalId) {
    OfficeService.list_by_hospital(hospitalId, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }

      $scope.offices = res.offices;
    });
  };

  $scope.removeItem = function (pos) {
    bootbox.setDefaults("locale", "zh_CN");
    bootbox.confirm("确定删除该医生信息吗", function (result) {
      if (result == true) {
        var doctor = $scope.displayed[pos];
        if (doctor) {
          var data = {id: doctor._id};
          DoctorService.delete(data, function (res) {
            if (res.result == true) {
              $scope.displayed.splice(pos, 1);
            } else {
              alert('删除数据失败');
            }
          }, function (data, status) {

          });
        } else {
          alert("请刷新重试");
        }
      }
    });
  };

  $scope.editDoctor = function (pos) {
    var targetDoctor = $scope.displayed[pos];
    DoctorData.set(targetDoctor);
    window.location = "#/update_doctor";
  }

  $scope.cancel = function () {
    window.location = '#/doctor_list';
  }

  $scope.role = $window.sessionStorage.role;
  $scope.hospital = $window.sessionStorage.hospital;

  if ($scope.role == 4 && $scope.hospital) {
    $scope.hospitalChanged($scope.hospital);
  }

  var data = DoctorData.get();
  if (data && !$.isEmptyObject(data)) {
    $scope.id = data._id;
    $scope.name = data.name;
    $scope.avatar = data.avatar;
    $scope.image_url = data.avatar;
    $scope.image_ready = (data.avatar != null);
    if ($scope.image_ready == true) {
      $('#preview>img').animate({width: '150'}, "slow");
    }
    $scope.province = data.province._id;
    HospitalService.list_by_province(data.province._id, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.hospitals = res.hospitals;
    });
    $scope.hospital = data.hospital._id;
    OfficeService.list_by_hospital(data.hospital._id, function (res) {
      if (res.result == false) {
        $scope.error_msg = res.message;
      }
      $scope.offices = res.offices;
    });
    $scope.office = data.office._id;
    $scope.title = data.title;
    $scope.major = data.major;
    $scope.phone = data.phone;
    $scope.introduce = data.introduce;
  }

  var options = {
    'expiration': Math.floor(new Date().getTime() / 1000) + 86400,
     bucket: 'vistrack-attach-prd',
    'save-key': '/{filemd5}{.suffix}'
  };
  // 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
  var policy = window.btoa(JSON.stringify(options));
  // 从 UPYUN 用户管理后台获取表单 API
  var form_api_secret = '5ri+TpAfi0lw+O9eaH9PBMYoSHI=';
  // 计算签名
  var signature = md5(policy + '&' + form_api_secret);
  var url_prefix = "http://" + options.bucket + ".b0.upaiyun.com";
  var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'pickfiles_doctor', // you can pass in id...
    container: document.getElementById('container_doctor'), // ... or DOM Element itself
    flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
    multi_selection:false,
    url: 'http://v0.api.upyun.com/' + options.bucket,

    multipart_params: {
      'Filename': '${filename}', // adding this to keep consistency across the runtimes
      'Content-Type': '',
      'policy': policy,
      'signature': signature
    },

    init: {
      PostInit: function () {
        //do nothing here.
      },

      FilesAdded: function (up, files) {
        plupload.each(files, function (file) {
          uploader.start();
          $(".progress").removeClass('hidden');
        });
      },

      UploadProgress: function (up, file) {
          $(".progress-bar").css("width", file.percent + '%');
          $(".progress-bar").html(file.percent + '%');
      },

      FileUploaded: function (up, file, info) {
        var response = JSON.parse(info.response);
        $scope.image = {};
        $scope.image_ready = true;
        $scope.image_url = url_prefix + response.url;
        $scope.avatar = url_prefix + response.url;
        $('#preview>img').animate({width: '150'}, "slow");

        $scope.$apply();
      },

      Error: function (up, err) {
        document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
      }
    }
  });
  uploader.init();
});
